#include "info_enter_manager.h"

void InfoEnterManager::enterInfo() {
    carsInfo.clear();
    studentsInfo.clear();
    for (size_t i = 0; i < 10; i++) {
        SmartCar item;
        string carId;
        string chasisId;
        cout << "请输入第" << i + 1 << "辆车的编号（cqusn打头的16位数字+字母）：" << endl;
        cin >> carId;
        cout << "请输入第" << i + 1 << "辆车的底盘编号（dp打头的8位数字+字母）：" << endl;
        cin >> chasisId;
        item.chassisId = chasisId;
        item.id = carId;
        carsInfo.push_back(item);
    }

    for (size_t i = 0; i < 10; i++) {
        cout << "请输入第" << i + 1 << "个学生的姓名和学号：" << endl;
        string name, stuId;
        cin >> name;
        cin >> stuId;
        Student item(name, stuId);
        studentsInfo.push_back(item);
    }
    cout << "输入完成！！" << endl;
}

void InfoEnterManager::assignStudent() {
    cout << "正在给学生分配智能小车..." << endl;
    sortCars();
    sortStudents();
    for (size_t i = 0; i < 10; i++) {
        auto stu = m_sortedStusInfo[i];
        m_sortedCarsInfo[i].assignStudent(stu.stuId, stu.stuName);
    }
    cout << "分配完成！！" << endl;
}

vector<SmartCar>& InfoEnterManager::getSortedCarsInfo() {
    return m_sortedCarsInfo;
}

void InfoEnterManager::sortCars() {
    for (auto car : carsInfo) {
        m_sortedCarsInfo.push_back(car);
    }
    // bubble sort
    for (size_t i = 10; i > 0; i--) {
        for (size_t j = 0; j < i - 1; j++) {
            long long current_id = getCarIdNumber(m_sortedCarsInfo[j]);
            long long after_id = getCarIdNumber(m_sortedCarsInfo[j + 1]);
            if (current_id > after_id) {
                // swap
                auto tmp = m_sortedCarsInfo[j];
                m_sortedCarsInfo[j] = m_sortedCarsInfo[j + 1];
                m_sortedCarsInfo[j + 1] = tmp;
            }
        }
    }
}

void InfoEnterManager::sortStudents() {
    for (auto stu : studentsInfo) {
        m_sortedStusInfo.push_back(stu);
    }
    // bubble sort
    for (size_t i = 10; i > 0; i--) {
        for (size_t j = 0; j < i - 1; j++) {
            int current_id = getStuIdNumber(m_sortedStusInfo[j]);
            int after_id = getStuIdNumber(m_sortedStusInfo[j + 1]);
            if (current_id > after_id) {
                // swap
                auto tmp = m_sortedStusInfo[j];
                m_sortedStusInfo[j] = m_sortedStusInfo[j + 1];
                m_sortedStusInfo[j + 1] = tmp;
            }
        }
    }
}

long long InfoEnterManager::getCarIdNumber(SmartCar car) {
    string num = car.id.substr(5, 11);
    return stoll(num);
}

int InfoEnterManager::getStuIdNumber(Student stu) {
    string num = stu.stuId.substr(0, 6);
    return stoi(num);
}
